package com.atguigu.flink.datastreamapi.agg;

import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * Created by Smexy on 2023/11/11

        reduce： 当你的聚合逻辑不是sum,max,min，需要自定义

 */
public class Demo3_Reduce
{
    public static void main(String[] args) {
        
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //聚合vc
        SingleOutputStreamOperator<WaterSensor> ds = env
            .socketTextStream("hadoop102", 8888)
            .map(new WaterSensorMapFunction());

        //按照key分组后的流
        KeyedStream<WaterSensor, String> ds2 = ds.keyBy(WaterSensor::getId);

        //常见的聚合方法，都是定义在KeyedStream类型中
        /*
               reduce聚合的要求：
                    输入和输出都是同一种类型
                    两两聚合
         */
        ds2
            .reduce(new ReduceFunction<WaterSensor>()
            {
                /*
                    有状态计算。
                    WaterSensor value1: 上一次聚合的结果
                    WaterSensor value2: 当前到达的这条数据
                        聚合之后的结果，向下游输出，也会再赋值给value1

                 */
                @Override
                public WaterSensor reduce(WaterSensor value1, WaterSensor value2) throws Exception {
                    System.out.println("Demo3_Reduce.reduce");
                    //模拟 maxBy(vc,false)的效果
                    //if (value2.getVc() >= value1.getVc()){
                    if (value2.getVc() > value1.getVc()){
                        // 模拟 maxBy(vc)的效果
                        return value2;
                    }else {
                        return value1;
                    }
                }
            })
            .print();


        try {
                            env.execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
        
    }
}
